<?php
/*
@author: wjf
@contact: Hurrican
@software: PhpStorm
@create: 2022/8/8 13:35
*/
declare(strict_types=1);
namespace app\store\service\agent;

use app\api\service\alipay\Payment;
use app\common\enum\setting\sms\Scene;
use app\common\enum\user\balanceLog\Scene as SceneEnum;
use app\common\model\CashOutLog;
use app\common\model\User;
use app\common\service\BaseService;
use app\store\model\agent\Rel;
use app\store\model\Setting;
use app\store\model\user\BalanceLog;
use think\Exception;
use think\facade\Config;
use think\facade\Db;
use think\facade\Log;

class Withdrawal  extends BaseService
{
    /**提现记录
     * @param $params
     * @return array
     */
    public function getRecords($params):array
    {
        $condition = [];
        if(!empty($params['between_time'])){
            $condition[] = ['fw_cashout_log.created_at','>=',$params['between_time'][0].' 00:00:00'];
            $condition[] = ['fw_cashout_log.created_at','<=',$params['between_time'][1].' 23:59:59'];
        }
        if(!empty($params['promoter_user_id'])){
            $condition[] = ['fw_cashout_log.user_id','=',$params['promoter_user_id']];
        }
        if(!empty($params['status']) || (isset($params['status']) && $params['status'] != '')){
            $condition[] = ['fw_cashout_log.status','=',$params['status']];
        }

        if($params['type'] == 'agent'){
            $agent_user_ids = Rel::where('is_del',0)->column(['promoter_user_id']);
            $condition[] = ['fw_cashout_log.user_id','IN',$agent_user_ids];
        }

        $userCon = [];
        if(!empty($params['search'])){
            $userCon[] = ['User.user_id|User.nick_name|User.mobile','like',"%{$params['search']}%"];
        }
        //进度是第二步才显示
        $condition[] = ['fw_cashout_log.process','=',2];
        return CashOutLog::with(['user'])
            ->field('fw_cashout_log.id,fw_cashout_log.order_no,fw_cashout_log.cash_type,
            fw_cashout_log.user_id,fw_cashout_log.amount,fw_cashout_log.status,
            fw_cashout_log.payment_time,fw_cashout_log.remark,fw_cashout_log.reason,fw_cashout_log.created_at')
            ->where($condition)
            ->hasWhere('user',$userCon)
            ->order('fw_cashout_log.id','DESC')
            ->paginate($params['limit'] ?? 15)
            ->each(function(&$item){
                $item['mobile'] = $item['user']['mobile'];
                $item['nick_name'] = $item['user']['nick_name'];
                unset($item['user']);
            })
            ->toArray();
    }


    /**流水号
     * @param $order_no
     */
    public function check($params):bool
    {
        $cash_log = CashOutLog::find($params['id']);
        if(!$cash_log){
            throwError('记录不存在');
        }
        if($cash_log->status != 0){
            throwError('记录已被审核，请勿重新审核');
        }
        Db::startTrans();
        try {
            $userModel = User::where(['user_id' => $cash_log->user_id,'is_delete' => 0])->find();
            if(!$userModel){
                throw new Exception('用户已被删除，无需审核');
            }
            if($userModel->withdrawal_price <= 0){
                throw new Exception('记录为改版之前记录，无需审核');
            }
            if($params['type'] == 1){
                //审核通过
//                if(Config::get('app.debug')){
//                    throw new Exception('测试环境请勿审核通过，否则提现余额将直接到账');
//                }
                $postData = [
                    'order_no' => $cash_log->order_no,
                    'amount' => $cash_log->amount,
                    'identity' => $cash_log->identity,
                    'name' => $cash_log->name,
                ];
                $aliPayment =  app(Payment::class);
                $res = $aliPayment->transfer($postData);
                Log::channel('cashout')->info('提现审核调用支付宝详情：'.json_encode($res));
                if(isset($res['status'])  && $res['status'] == 'SUCCESS' ) {
                    //提现成功
                    $cash_log->trans_no = $res['pay_fund_order_id']; //流水号
                    $cash_log->reason = $res['msg'];
                    $cash_log->status = 1;
                    // 新增余额变动记录
                    BalanceLog::add(SceneEnum::CASHOUT, [
                        'user_id' => $cash_log->user_id,
                        'money' => $cash_log->amount * -1,
                    ], ['order_no' => $cash_log->order_no]);
                    $userModel->withdrawal_price = Db::raw('withdrawal_price-' . $cash_log->amount);
                }else{
                    //提现失败
                    $cash_log->status = -1;
                    $cash_log->reason =  $res['sub_msg'] ?? '';
                    $userModel->withdrawal_price = Db::raw('withdrawal_price-' . $cash_log->amount);
                    $userModel->balance = Db::raw('balance+' . $cash_log->amount);
                }
            }else{
                //人工审核失败
                $cash_log->status = -1;
                $cash_log->reason =  $params['remark'] ?? '人工审核失败';
                $userModel->withdrawal_price = Db::raw('withdrawal_price-' . $cash_log->amount);
                $userModel->balance = Db::raw('balance+' . $cash_log->amount);
            }
            $cash_log->remark = $params['remark'] ?? '';
            $cash_log->save();
            $userModel->save();
            Db::commit();
            return true;
        }catch (\Exception $exception){
            Db::rollBack();
            throwError($exception->getMessage());
            return false;
        }

    }

    /**AI状态开关
     * @return int
     */
    public function getAiStatus():array
    {
        $condition = [
            ['key','=','cash_ai_check']
        ];
        $setting = Setting::where($condition)->find();
        return [
            'is_ai_check' => $setting->status ?? 0
        ];
    }

    /**AI审核开关
     * @param $params
     * @return bool
     */
    public function getAiSet($params):bool
    {
        $condition = [
            ['key','=','cash_ai_check']
        ];
        $setting = Setting::where($condition)->find();
        if(!$setting){
            Setting::create([
                'key' => 'cash_ai_check',
                'describe' => '提现自动审核',
                'values' => json_encode(['is_ai_check' => $params['status']]),
                'status' => $params['status']
            ]);
        }else{
            $setting->status = $params['status'];
            $setting->values = ['is_ai_check' => $params['status']];
            $setting->save();
        }
        return true;
    }

}